package 知识点复习.异步回调.设置子任务回调钩子;

import java.util.concurrent.CompletableFuture;
import java.util.function.BiConsumer;
import java.util.function.Function;

public class CompletableFutureDemo1 {
    public static void whenCompleteDemo() throws Exception {
        //创建异步任务
        CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
            try {
                //模拟执行一秒
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            System.out.println(Thread.currentThread().getName() + ":抛出异常");
            throw new RuntimeException(Thread.currentThread().getName() + ":发生异常");
        });
        //设置异步任务执行完成后的回调钩子
        future.whenComplete(new BiConsumer<Void, Throwable>() {
            @Override
            public void accept(Void unused, Throwable throwable) {
                System.out.println(Thread.currentThread().getName() + ":执行完成!");
            }
        });

        //设置异步任务发生异常后的回调钩子
        future.exceptionally(new Function<Throwable, Void>() {
            @Override
            public Void apply(Throwable throwable) {
                System.out.println(Thread.currentThread().getName() + ":执行失败！" + throwable.getMessage());
                return null;
            }
        });
        //获取异步任务的结果
        future.get();
    }

    public static void main(String[] args) throws Exception {
        whenCompleteDemo();
    }
}
